# ----------------------------------------------------------------------
# ' this file uses opioid prescription files for each quarter
# ' to generate the list of first time each person received the opioids
# ' by BK (bl11@indiana.edu)
# ----------------------------------------------------------------------

load_library = c('bit64','data.table','fst','future.apply','stringr','logger')
invisible(lapply(load_library, function(x) library(x, character.only=TRUE, quietly= TRUE)))
options(scipen=999)

bucket = file.path('/N','project','iuni_doctorshopping')

pat_list_files = dir(file.path(bucket,'derived_v4_202101','patient_list','ses','opioid'),full.names=TRUE)

all_pat = lapply(pat_list_files, function(ff){
	dt = fread(ff)
	yy_qq = extract_year_quarter_from_filename(ff)$year_quarter
	dt[, year_quarter := yy_qq]
	return(dt)
}) %>% rbindlist()

all_pat[, year := substr(year_quarter, 1, 4)]
all_pat[, quarter := substr(year_quarter, 6, 6)]
all_pat[, date := zoo::as.Date(zoo::as.yearqtr(paste0(year,' Q',quarter)))]

# select when patients take the opioid first time
all_pat = all_pat[all_pat[, .I[which.min(date)], by='PATID']$V1]
all_pat = all_pat[, c('PATID','year','quarter')]
#object.size(all_pat) %>% format('Gb')

write_fst(all_pat, file.path(bucket,'derived_v4_202101','patient_list','ses','first_opioid_prescription.fst'), 100)





